import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Row, Col, Button, Modal, Input, InputNumber } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';
import MyTree from '../../components/_public/MyTree';
import styles from './OutExam.less';
import EditTableTest from '../../components/_public/EditTableTest';
import { getParamUrl, minHeight, heightThreeMain, myMessage } from '../../utils/formatDataSource';

@connect(({ lesson3, question3, loading }) => ({
  lesson:lesson3,
  question:question3,
  treeLoading: loading.effects['lesson3/kjConfig'],
}))
class InExamConfig extends PureComponent {
  state = {
    lessonId: '',
    currentAdd: 1, // 当前添加的题目类型  1 填空  2 选择  3 简答
    visible: false,
    addBtnDisabled: true,
    examTime: 90,
    treeKeys: [],
    totalTreeKeys: [],
    questionTypeIds: [], // 选中的所有题型ID
    questionList: [],
    selectedRowKeys: [],
    totalScore: 0,
    totalScoreJd: 0,
    scoreModal: false,
  };

  componentDidMount() {
    const { dispatch, location: { search } } = this.props;
    dispatch({
      type: 'lesson3/kjConfig',
    });
    const params = getParamUrl(search);
    this.setState({
      lessonId: params.lessonId,
    });
    dispatch({
      type: 'question3/homeworkInfo',
      payload: params,
    });
    const type = params.type;
    if (type !== undefined) {
      dispatch({
        type: 'question3/getHistory',
        payload: {
          lessonId: params.lessonId,
          type: 1,
        },
      }).then(() => {
        const { examHistory } = this.props.question;
        const { selectedRowKeys } = this.state;
        const { jd_data, totalScore, examTime, treeKeys, totalTreeKeys } = examHistory;
        if (!treeKeys) {
          return;
        }
        const questionTypeIds = [];
        this._m_m1(this.props.lesson.treeList, treeKeys, questionTypeIds);
        const disabled = treeKeys.length === 0 ? true : false;
        // jd_data.sort((a, b) => {
        //   if(a.refId === b.refId) {
        //     return a.id - b.id;
        //   }
        //   else {
        //     return a.refId - b.refId;
        //   }
        // });
        this.setState({
          questionList: jd_data,
          examTime,
          totalScore,
          treeKeys,
          totalTreeKeys,
          selectedRowKeys,
          addBtnDisabled: disabled,
          questionTypeIds,
        });
      });
    }
  }

  /**
   * 递归获取当前知识树中所有被选中的题型ID
   * @param data
   * @param keys
   * @param questionTypeIds
   * @private
   */
  _m_m1 = (data, keys, questionTypeIds) => {
    data.map(d => {
      if (d.sons) {
        this._m_m1(d.sons, keys, questionTypeIds);
      }
      if (d.type === 4) {
        keys.map(k => {
          if (k === d.uniqueKey) {
            questionTypeIds.push(d.id);
          }
        });
      }
    });
  };
  _m1 = (checkedKeys, totalKeys) => {
    const { treeList } = this.props.lesson;
    const questionTypeIds = [];
    let addBtnDisabled = true;
    this._m_m1(treeList, totalKeys, questionTypeIds);
    if (questionTypeIds.length !== 0) {
      addBtnDisabled = false;
    }
    this.setState({
      treeKeys: checkedKeys,
      totalTreeKeys: totalKeys,
      questionTypeIds: questionTypeIds,
      addBtnDisabled,
    });
  };
  _m8 = () => {
    let selectedData = [];
    const { questionList, treeKeys, totalTreeKeys, totalScore } = this.state;
    selectedData = [...questionList];
    const { dispatch, question: { lessonId } } = this.props;
    if (selectedData.length === 0) {
      myMessage.error('请先添加题目', 2);
      return;
    }
    const error = selectedData.filter(s => s.score === '请设置分数');
    if (error.length > 0) {
      myMessage.error('请设置分数', 2);
      return;
    }
    const selectedTrees = treeKeys.join(',');
    const totalTrees = totalTreeKeys.join(',');
    dispatch({
      type: 'question3/saveList',
      payload: {
        questionList: selectedData,
        lessonId,
        type: 1,
        time: this.state.examTime,
        selectedTrees,
        totalTrees,
        totalScore,
      },
    });
  };
  changeExamTime = e => {
    this.setState({
      examTime: e,
    });
  };
  updateTotalScore = total => {
    this.setState({ totalScore: total });
  };
  updateQuestions = questionList => {
    this.setState({ questionList });
  };
  render() {
    const { treeList = [] } = this.props.lesson;
    const { homeworkInfo = {} } = this.props.question;
    const { selectedRowKeys, currentAdd, questionList } = this.state;
    const exist = selectedRowKeys.filter(s => s.type === currentAdd);
    const data =
      exist.length === 0
        ? {
            data: [],
            page: 1,
          }
        : exist[0];

    return (
      <PageHeaderLayout>
        <Col span={9}>
          <Card style={{ minHeight: minHeight }}>
            <MyTree
              dataSource={treeList}
              checkedKeys={this.state.treeKeys}
              handleCheck={this._m1}
              loading={this.props.treeLoading}
            />
          </Card>
        </Col>
        <Col span={15}>
          <Card style={{ marginBottom: '10px', textAlign: 'right' }}>
            <Button
              type="primary"
              size="small"
              onClick={() =>
                this.props.dispatch(
                  routerRedux.push(`/lesson/3/lesson-info?lessonId=${this.state.lessonId}`)
                )
              }
            >
              返回
            </Button>
          </Card>
          <Card bordered={false}>
            <Row>
              <Col span={7}>
                上课时间：<strong>{homeworkInfo.formatDateStr}</strong>
              </Col>
              <Col span={4}>
                上课状态：<strong>{homeworkInfo.lessonStatus}</strong>
              </Col>
              <Col span={4}>
                备课状态：<strong>{homeworkInfo.bkStatus}</strong>
              </Col>
            </Row>
          </Card>
          <EditTableTest
            data={questionList}
            type={3}
            questiontypeId={this.state.questionTypeIds.join(',')}
            where="in"
            updateTotalScore={this.updateTotalScore}
            updateData={this.updateQuestions}
          />
          <Card bordered={false}>
            <Row type="flex" align="middle">
              <Col span={2}> 考试时间：</Col>
              <Col span={3}>
                {' '}
                <InputNumber
                  value={this.state.examTime}
                  onChange={this.changeExamTime}
                  min={1}
                  max={1000}
                />
              </Col>
              <Col span={5}> 考试分数：{this.state.totalScore}分</Col>
              <Col span={14} style={{ textAlign: 'right' }}>
                <Button type="primary" onClick={this._m8}>
                  保存
                </Button>&nbsp;&nbsp;&nbsp;&nbsp;
              </Col>
            </Row>
          </Card>
        </Col>
      </PageHeaderLayout>
    );
  }
}

export default InExamConfig;
